package com.chen.controller;

import com.chen.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * redis分布式计数，模拟库存扣减
 */
@RestController
@RequestMapping("/")
public class DistributeCounterController {

    private static final String STORE_KEY = "store";

    private static final Object lock = new Object();

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 初始化库存
     * @param store 初始库存
     */
    @GetMapping("/store/{store}")
    public String initStore(@PathVariable("store") Integer store){
        redisUtil.set(STORE_KEY,store.toString());
        return "库存初始化成功，初始库存为"+store;
    }

    /**
     * 查询库存
     */
    @GetMapping("/get")
    public String getStore(){
        return (String) redisUtil.get(STORE_KEY);
    }

    @GetMapping("/miaosha")
    public String decrease(){
        synchronized (lock){
            if (!redisUtil.hasKey(STORE_KEY)){
                return "秒杀结束！";
            }
            Integer store =Integer.valueOf((String)redisUtil.get(STORE_KEY)) ;
            if (store <= 0 ){
                redisUtil.del(STORE_KEY);
                return "秒杀结束！";
            }else {
                redisUtil.desc(STORE_KEY,1);
                return "秒杀成功";
            }
        }
    }
}
